package com.lx.fav.servlet;

import com.lx.fav.entity.Fav;
import com.lx.fav.entity.User;
import com.lx.fav.service.BizException;
import com.lx.fav.service.impl.FavServiceImpl;
import com.lx.fav.util.Utils;
import com.lx.fav.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addFav")
public class AddFavServlet extends HttpServlet {

    FavServiceImpl biz = new FavServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受参数, 封装fav 对象
        Fav fav = new Fav();
        fav.setName(req.getParameter("name"));
        fav.setAddr(req.getParameter("addr"));
        fav.setIntro(req.getParameter("intro"));
        fav.setImage(req.getParameter("image"));
        fav.setTags(req.getParameter("tags"));

        Result ret = null;
        // 获取会话中用户的id, 设置到 fav.uid
        User userInfo = (User)req.getSession().getAttribute("userInfo");
        if(userInfo == null){
            ret = new Result(-6, "未登录,无法操作", null);
        }else {
            fav.setUid(userInfo.getId());
            //调用业务层方法
            try {
                biz.create(fav);
                ret = new Result(1, "链接添加成功", fav);
            } catch (BizException e) {
                ret = new Result(e.getCode(), e.getMessage(), null);
            }
        }

        Utils.outPut(resp, ret);
        //调用业务层方法
        //捕获异常，输出结果

    }
}
